from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from ..core.database import get_db
from ..core.config import settings
from ..services.auth_service import AuthService
from ..services.module_service import ModuleService
from ..schemas.user import UserCreate, User as UserSchema, PasswordChange, PasswordResetRequest, PasswordReset
from ..schemas.module import AdminModulesResponse
from ..core.dependencies import get_current_user
from ..models.user import User

router = APIRouter(prefix="/auth", tags=["authentication"])
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")

@router.post("/register", response_model=UserSchema)
def register(user: UserCreate, db: Session = Depends(get_db)):
    """用户注册 - 只能注册普通用户"""
    auth_service = AuthService(db)
    
    # 检查用户名是否已存在
    db_user = auth_service.get_user_by_username(user.username)
    if db_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已被注册"
        )
    
    # 检查邮箱是否已存在
    db_user = db.query(User).filter(User.email == user.email).first()
    if db_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="邮箱已被注册"
        )
    
    # 创建用户，默认是普通用户
    new_user = auth_service.create_user(user)
    
    # 确保只有admin是超级用户
    auth_service.ensure_only_admin_is_superuser()
    
    return new_user

@router.get("/test")
def test_route():
    """测试路由，用于验证auth路由是否正常工作"""
    return {"message": "Auth API is working!"}

@router.post("/login")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """登录函数，支持管理员获取模块列表"""
    # 1. 验证用户名和密码
    auth_service = AuthService(db)
    user = auth_service.authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 2. 检查用户是否激活
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户已被禁用"
        )
    
    # 3. 生成访问令牌
    access_token = auth_service.create_access_token(data={"sub": user.username})
    
    # 4. 构建响应数据
    response_data = {
        "access_token": access_token,
        "token_type": "bearer",
        "username": user.username,
        "is_superuser": user.is_superuser
    }
    
    # 5. 如果是管理员用户，尝试获取模块列表
    if user.is_superuser:
        print("当前用户是管理员，尝试获取模块列表...")
        try:
            print("创建ModuleService实例...")
            module_service = ModuleService(db)
            
            print("调用get_active_modules方法...")
            active_modules = module_service.get_active_modules()
            
            print(f"获取到的激活模块数量: {len(active_modules)}")
            
            # 将模块转换为简单的列表格式，不包含复杂的树形结构
            modules_list = [
                {
                    "id": module.id,
                    "name": module.name,
                    "code": module.code,
                    "icon": module.icon,
                    "route": module.route,
                    "parent_id": module.parent_id,
                    "order": module.order
                }
                for module in active_modules
            ]
            
            response_data["modules"] = modules_list
            print("模块列表已成功添加到响应数据中")
        except Exception as e:
            # 如果获取模块列表失败，记录错误但仍然返回登录成功的响应
            import traceback
            print(f"获取模块列表失败: {str(e)}")
            print(f"详细错误堆栈: {traceback.format_exc()}")
    
    return response_data

@router.post("/change-password")
def change_password(
    password_data: PasswordChange,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """修改密码"""
    auth_service = AuthService(db)
    
    # 验证当前密码
    if not auth_service.verify_password(password_data.current_password, current_user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前密码错误"
        )
    
    # 更新密码
    current_user.hashed_password = auth_service.get_password_hash(password_data.new_password)
    current_user.updated_at = auth_service.get_current_time()
    db.commit()
    
    return {"message": "密码修改成功"}

@router.post("/forgot-password")
def forgot_password(request: PasswordResetRequest, db: Session = Depends(get_db)):
    """忘记密码 - 发送重置邮件"""
    auth_service = AuthService(db)
    user = auth_service.get_user_by_email(request.email)
    
    if not user:
        # 为了安全，不透露用户是否存在
        return {"message": "如果邮箱存在，重置链接已发送到您的邮箱"}
    
    # 生成重置令牌
    reset_token = auth_service.create_password_reset_token(user.email)
    
    # 在实际环境中，这里应该发送邮件
    # 为了演示，我们返回令牌
    return {
        "message": "重置链接已生成",
        "reset_token": reset_token,
        "note": "这是演示模式，实际环境会发送邮件"
    }

@router.post("/reset-password")
def reset_password(reset_data: PasswordReset, db: Session = Depends(get_db)):
    """重置密码"""
    auth_service = AuthService(db)
    
    # 验证重置令牌
    email = auth_service.verify_password_reset_token(reset_data.reset_token)
    if not email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="重置链接已过期或无效"
        )
    
    # 获取用户
    user = auth_service.get_user_by_email(email)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 更新密码
    user.hashed_password = auth_service.get_password_hash(reset_data.new_password)
    user.updated_at = auth_service.get_current_time()
    db.commit()
    
    return {"message": "密码重置成功"}

@router.get("/me", response_model=UserSchema)
def get_current_user_info(current_user: User = Depends(get_current_user)):
    """获取当前用户信息"""
    return current_user